import router, { asyncRoutes } from './router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import store from './store'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  NProgress.start()

  // 1. 如果有token
  if (store.getters.token) {
    // 1.1 如果去的是登录页 直接跳转到主页
    if (to.path === '/login') {
      next('/')
      NProgress.done()
      return
    }
    // 1.2 有token 但是没有用户信息 就获取用户信息
    if (!store.getters.name) {
      await store.dispatch('user/getUserInfoAction')
      // 获取用户有什么菜单
      const user = store.state.user
      const menus = user.userInfo.roles.menus
      // 过滤权限
      const newList = asyncRoutes.filter(v => {
        // return menus.includes(v.path.slice(1))
        return menus.includes(v.name)
      })
      // 追加路由
      router.addRoutes([...newList, { path: '*', redirect: '/404', hidden: true }])
      // 更新到vuex
      store.commit('user/setRoutes', newList)
      next(to.path)
    }
    next()
    return
  }

  // 2. 没有token
  // 2.1 去的是白名单 直接放行
  if (whiteList.includes(to.path)) {
    next()
    return
  }

  // 2.2 去的不是白名单, 直接跳转到登录页
  next('/login')
  NProgress.done()
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
